package com.loren.oauth.converter;

import com.loren.oauth.data.dto.JwtUserInfo;
import com.loren.oauth.data.dto.SecurityUserInfo;
import com.loren.oauth.data.dto.UserAuthInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.Map;

public class CustomJwtAccessTokenConverter extends JwtAccessTokenConverter {

	@Override
	public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
		SecurityUserInfo securityUserInfo = (SecurityUserInfo) authentication.getPrincipal();
		UserAuthInfo userAuthInfo = securityUserInfo.getUserAuthInfo();
        JwtUserInfo jwtUserInfo = new JwtUserInfo();
        BeanUtils.copyProperties(userAuthInfo, jwtUserInfo);

		DefaultOAuth2AccessToken defaultOAuth2AccessToken = new DefaultOAuth2AccessToken(accessToken);
		Map<String, Object> additionalInformation = defaultOAuth2AccessToken.getAdditionalInformation();
        additionalInformation.put("extend", jwtUserInfo);
        
		return super.enhance(defaultOAuth2AccessToken, authentication);
	}
	
	@Override
	public OAuth2Authentication extractAuthentication(Map<String, ?> claims) {
		OAuth2Authentication authentication = super.extractAuthentication(claims);
		authentication.setDetails(claims);
		return authentication;
	}
}
